package org.misalen.web.support.util;

import java.io.InputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class StringUtil {
	static {
		InputStream istream = null;
		try {
			istream = StringUtil.class.getResourceAsStream("../../../../log4j.properties");
			Properties props = new Properties();
			props.load(istream);
			istream.close();
			new PropertyConfigurator().doConfigure(props, LogManager.getLoggerRepository());
		} catch (Exception e) {
			System.err.println(e);
		} finally {
			if (istream != null) {
				try {
					istream.close();
				} catch (Exception ignore) {
				}
			}
		}
	}

	public static String formatTimestamp(Date date) {

		if (date == null) {
			return "";
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		return sdf.format(date);
	}

	public static String formatDate(Date date) {
		if (date == null) {
			return "";
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}

	public static boolean isNullOrEmpty(String text) {
		return text == null || text.isEmpty();
	}

	public static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * log
	 * 
	 * @param category
	 *            类型
	 * @param log
	 *            内容
	 */
	public static void log(String category, Object log) {
		if (log == null) {
			log = "";
		}
		Logger logger = Logger.getLogger(category);
		logger.info(log.toString());
	}
}
